package org.xiaojl.modules.sys.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.dwz.PageBean;
import org.xiaojl.dwz.PageParam;
import org.xiaojl.modules.sys.entity.SysRole;
import org.xiaojl.modules.sys.entity.SysUserRole;
import org.xiaojl.modules.sys.service.SysRoleResourceService;
import org.xiaojl.modules.sys.service.SysRoleService;
import org.xiaojl.modules.sys.service.SysUserRoleService;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 系统角色 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Controller
@RequestMapping("/sys/sysRole")
public class SysRoleController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SysRoleController.class);
	private static final String basePagePath = "sys/role/";

	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleResourceService sysRoleResourceService;
	
	
	@RequiresPermissions("sys/sysRole/list")
	@RequestMapping("/list")
	public ModelAndView list(Model model, PageParam pageParam, SysRole sysRole){
		try {
			PageBean<SysRole> pageBean = this.selectListPage(pageParam, sysRole, sysRoleService);
			
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("pageParam", pageParam);
			model.addAttribute("entity", sysRole);
			
			return operatePage(basePagePath+"list",model);
		} catch (Exception e) {
			log.error("查询列表数据出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	
	/**
	 * 转到添加角色页面 .
	 * 
	 */
	@RequiresPermissions("sys/sysRole/add")
	@RequestMapping("/addUI")
	public ModelAndView addUI(Model model) {
		try {
			
			return operatePage(basePagePath+"add",model);
			
		} catch (Exception e) {
			log.error("进入添加页面出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存新添加的一个角色 .
	 * 
	 */
	@RequiresPermissions("sys/sysRole/add")
	@RequestMapping("/add")
	public ModelAndView add(SysRole sysRole, DwzAjax dwz) {
		try {
			List<SysRole> listByName = sysRoleService.selectList(new EntityWrapper<SysRole>().eq("name",sysRole.getName()));
			if (ToolUtil.isNotEmpty(listByName)) {
				return operateError("角色名【" + sysRole.getName() + "】已存在");
			}

			sysRole.setCreateBy(WebUtil.getSessionUser(request).getSysUser().getId());
			sysRoleService.insert(sysRole);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败");
		}
	}
	
	/**
	 * 转到角色修改页面 .
	 * 
	 */
	@RequiresPermissions("sys/sysRole/edit")
	@RequestMapping("/editUI")
	public ModelAndView editUI(Model model, Long roleId) {
		try {
			SysRole sysRole = sysRoleService.selectById(roleId);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("获取数据失败");
			}
			
			if("系统管理员".equals(sysRole.getName())){
				return operateError("[系统管理员]角色信息不支持修改！");
			}

			model.addAttribute("sysRole",sysRole);
			return operatePage(basePagePath+"edit",model);
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:roleId="+roleId, e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存修改后的角色信息 .
	 * 
	 */
	@RequiresPermissions("sys/sysRole/edit")
	@RequestMapping("/edit")
	public ModelAndView edit(SysRole role, DwzAjax dwz) {
		try {
			Long id = role.getId();
			SysRole sysRole = sysRoleService.selectById(id);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("无法获取要修改的数据");
			}
			
			if(!sysRole.getName().equals(role.getName())){
				List<SysRole> listByName = sysRoleService.selectList(
						new EntityWrapper<SysRole>().eq("name",role.getName()));
				if (ToolUtil.isNotEmpty(listByName)) {
					return operateError("角色名【" + role.getName() + "】已存在");
				}
			}

			sysRoleService.updateById(role);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("保存失败");
		}
	}
	
	/**
	 * 删除一个角色
	 * 
	 */
	@RequiresPermissions("sys/sysRole/delete")
	@RequestMapping("/delete")
	public ModelAndView delete(Long roleId, DwzAjax dwz) {
		try {
			SysRole sysRole = sysRoleService.selectById(roleId);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("无法获取要删除的角色");
			}
			if("系统管理员".equals(sysRole.getName())){
				return operateError("[系统管理员]角色信息不支持删除！");
			}
			
			// 判断是否有操作员关联到此角色
			List<SysUserRole> urlist = sysUserRoleService.selectList(new EntityWrapper<SysUserRole>().eq("roleId", roleId));
			if (ToolUtil.isNotEmpty(urlist)) {
				return operateError("有【" + urlist.size() + "】个用户关联到此角色，要先解除所有关联后才能删除!");
			}
			
			//级联删除
			sysRoleService.deleteWithCascade(roleId);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("删除角色信息出现异常:roleId="+roleId, e);
			return operateError("删除失败");
		}
	}
	
	
	/**
	 * 分配角色菜单UI：sys_role_resource
	 */
	@RequiresPermissions("sys/sysRole/assignMenu")
	@RequestMapping("/assignMenuUI")
	public ModelAndView assignMenuUI(Model model,Long roleId) {

		SysRole sysRole = sysRoleService.selectById(roleId);
		if (ToolUtil.isEmpty(sysRole)) {
			return operateError("无法获取要分配资源的角色");
		}
		//查询该角色下的所有菜单
		String resourceIds = sysRoleResourceService.selectResourceIdsByRoleId(roleId);
		
		String resourcesTree = sysRoleService.selectResourcesTreeByAssign(resourceIds);
		
		model.addAttribute("resourceIds", resourceIds);
		model.addAttribute("resourcesTree", resourcesTree);
		model.addAttribute("role", sysRole);
		return operatePage(basePagePath+"/assignMenu",model);
	}
	
	@RequiresPermissions("sys/sysRole/assignMenu")
	@RequestMapping("/assignMenu")
	public ModelAndView assignMenu(Long roleId, String selectVal, DwzAjax dwz){
		try {
			SysRole sysRole = sysRoleService.selectById(roleId);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("无法获取要资源的角色");
			}
			
			sysRoleResourceService.updateRoleResourceByRoleId(roleId,selectVal);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("分配角色菜单权限出现异常:roleId="+roleId, e);
			return operateError("分配角色菜单权限失败");
		}
		
	}
	
}
